$(function () {
    //初始必填项
    validateRule()
    //搜索信息
    var $userTableForm = $(".daliyShow-table-form");
    //表单查询
    var settings = {
        url: ctx + "dailyShow/list",
        pageSize: 10,
        queryParams: function (params) {
            return {
                pageSize: params.limit,
                pageNum: params.offset / params.limit + 1,
                //项目代码
                projectNo: $userTableForm.find("input[name='projectNo']").val(),
                //角色
                roleName: $userTableForm.find("select[name='roleName']").val(),
                //部门
                deptName: $userTableForm.find("select[name='deptName']").val(),
                //创建人
                //creation: $userTableForm.find("select[name='creation']").val(),
                creation: $("#creation").val(),
                //日期从
                // stateDate: $userTableForm.find("select[name='stateDate']").val(),
                stateDate: $("#stateDate").val(),
                //日期到
                //endDate: $userTableForm.find("select[name='endDate']").val(),
                endDate: $("#endDate").val(),
                //是否合格
                isQualified: $userTableForm.find("select[name='isQualified']").val(),
                //测试类型
                articleType: $userTableForm.find("select[name='articleType']").val(),
            };
        },
        columns: [{
            checkbox: true
        }, {
            field: 'id',
            visible: false
        }, {
            field: 'percent',
            visible: false
        }, {
            field: 'userId',
            visible: false
        }, {
            field: 'projectNo', align: 'center', width: 100,
            title: '项目代号',
            cellStyle:{
                css:{'word-wrap': 'break-word','word-break': 'break-all'}
            }
        }, {
            field: 'articleType', align: 'center',width: 100,
            title: '测试类型'
        }, {
            field: 'articleNumber', align: 'center',width: 70,
            title: '用例条数'
        },/* {
            field: 'plannedLaborHours', align: 'center',width: 70,
            title: '计划时间'
        }, {
            field: 'actuaLinputHours', align: 'center',width: 70,
            title: '实际时间'
        }, {
            field: 'executioneFficiency', align: 'center',width: 70,
            title: '执行效率'
        },*/ {
            field: 'plannedLaborHours', width: 140, align: 'center',
            title: '计划/实际=效率',formatter:function (valuer, row, index) {
                //计划时间
                var  plannedLaborHours = valuer;
                //实际时间
                var  actuaLinputHours = row.actuaLinputHours;
                //效率
                var  executioneFficiency = row.executioneFficiency;
                //组合
                return plannedLaborHours+"/"+actuaLinputHours+"="+ executioneFficiency;
            }
        }, {
            field: 'inputContent', align: 'center', width: 170,
            title: '投入内容'
        }, {
            field: 'reasonsforeFficiencyFailure', width: 170, align: 'center',
            title: '效率不达标原因'
        }, {
            field: 'roleName', align: 'center', width: 130,
            title: '角色部门', formatter: function (valuer, row, index) {
                //角色
                var roleName = valuer;
                //部门
                var deptName = row.deptName;
                return roleName + ":" + deptName;
            }

        },/* {
            field: 'deptName', align: 'center',
            title: '部门'
        },*/ {
            field: 'month', align: 'center',width: 50,
            title: '日期', formatter: function (valuer, row, index) {
                //日期
                var month = valuer;
                //号
                var mark = row.mark;
                return month + "月" + mark + "日";
            }
        },/* {
            field: 'mark', align: 'center',
            title: '号'
        },*/ {
            field: 'creationTime', align: 'center',width: 100,
            title: '申请时间'
        }, {
            field: 'creation', align: 'center',width: 100,
            title: '申请人'
        }

        ]
        //不及格文字变颜色
        /*,rowStyle:function (row,index) {
            if (row.percent < 90){
                return {css:{'color':'red'}};
            }
            return "";
        }*/
    };
    //重载表格
    $MB.initTable('dailyShowTable', settings);

});

//搜索
function search() {
    $MB.refreshTable('dailyShowTable');
}

//刷新
function refresh() {
    //清空form表单
    $(".daliyShow-table-form")[0].reset();
    search();
}


//导出excel
function exportUserExcel() {
    $.post(ctx + "dailyShow/excel", $(".daliyShow-table-form").serialize(), function (r) {
        if (r.code === 0) {
            window.location.href = "common/download?fileName=" + r.msg + "&delete=" + true;
        } else {
            $MB.n_warning(r.msg);
        }
    });
}

//导出Csv
function exportUserCsv() {
    $.post(ctx + "dailyShow/csv", $(".daliyShow-table-form").serialize(), function (r) {
        if (r.code === 0) {
            window.location.href = "common/download?fileName=" + r.msg + "&delete=" + true;
        } else {
            $MB.n_warning(r.msg);
        }
    });
}

//删除日报
function deleteUsers() {
    //获取勾选的数据
    var selected = $("#dailyShowTable").bootstrapTable('getSelections');
    //数据的长度
    var selected_length = selected.length;
    //数据的判断
    var contain = false;
    if (!selected_length) {
        $MB.n_warning('请勾选需要删除的日报！');
        return;
    }

    //循环取到id值
    var id = "";
    for (var i = 0; i < selected_length; i++) {
        id += selected[i].id;
        if (i !== (selected_length - 1)) id += ",";
    }
    //删除
    $MB.confirm({
        text: "确定删除选中日报？",
        confirmButtonText: "确定删除"
    }, function () {
        $.post(ctx + 'dailyShow/delete', {"id": id}, function (r) {
            if (r.code === 0) {
                $MB.n_success(r.msg);
                refresh();
            } else {
                $MB.n_danger(r.msg);
            }
        });
    });
}

//修改日报
function updateUser() {
    var selected = $("#dailyShowTable").bootstrapTable('getSelections');
    var selected_length = selected.length;
    if (!selected_length) {
        $MB.n_warning('请勾选需要修改的用户！');
        return;
    }
    if (selected_length > 1) {
        $MB.n_warning('一次只能修改一个用户！');
        return;
    }
    //修改的页面
    var $form = $('#daily-Update-form');
    //选中的对象的数据
    var date = selected[0];
    //赋值
    //项目代码
    $form.find("input[name='projectNo']").val(date.projectNo);
    //投入内容
    $form.find("input[name='inputContent']").val(date.inputContent);
    //计划投入工时
    $form.find("input[name='plannedLaborHours']").val(date.plannedLaborHours);
    //实际投入工时
    $form.find("input[name='actuaLinputHours']").val(date.actuaLinputHours);
    //执行效率
    $form.find("input[name='executioneFficiency']").val(date.executioneFficiency).attr("readonly", true);
    //效率不达标原因
    $form.find("input[name='reasonsforeFficiencyFailure']").val(date.reasonsforeFficiencyFailure);
    //日报id
    $form.find("input[name='id']").val(date.id);
    //用户id
    $form.find("input[name='userId']").val(date.userId);
    //用例条数
    $form.find("input[name='articleNumber']").val(date.articleNumber);

    //开启修改日报页面
    $('#dailyShow-update').modal('show');

}

//提交监听
$(".btn-saveUpdate").click(function () {
    var name = $(this).attr("name");
    //关闭窗口
    if (name == 'close_Update') {
        //关闭修改日报页面
        $('#dailyShow-update').modal('hide');
        //清空表单
        $("#daily-Update-form")[0].reset();

        //提交修改
    } else if (name == 'saveUpdate') {
        var validator = $("#daily-Update-form").validate();
        var flag = validator.form();
        if (flag) {
            $.post(ctx + "dailyShow/Update", $("#daily-Update-form").serialize(), function (r) {
                if (r.code === 0) {
                    //关闭修改日报页面
                    $('#dailyShow-update').modal('hide');
                    //清空表单
                    $("#daily-Update-form")[0].reset();
                    search();
                    $MB.n_success(r.msg);
                } else {
                    $MB.n_danger(r.msg);
                }
            });
        }
    }


});

/**
 * 设置必填
 */
function validateRule() {
    //获取修改的数据
    var $dailyTableForm = $("#daily-Update-form");
    var icon = "<i class='zmdi zmdi-close-circle zmdi-hc-fw'></i> ";
    //效验是否填写过
    validator = $dailyTableForm.validate({
        rules: {
            //项目码
            projectNo: {
                required: true
            },
            //计划投入工时
            plannedLaborHours: {
                required: true
            },
            //实际投入工时
            actuaLinputHours: {
                required: true
            },
            //投入内容
            inputContent: {
                required: true
            },
            //用例条数
            articleNumber: {
                required: true
            },

        },
        messages: {
            projectNo: icon + "项目不能为空",
            plannedLaborHours: icon + "计划投入工时不能为空",
            actuaLinputHours: icon + "实际投入工时不能为空",
            inputContent: icon + "投入不能为空",
            articleNumber: icon + "用例条数不能为空",
        }
    });
}

/**
 * 补录日报
 */
function supplement() {
    //开启校验时间input
    $("#ifSupplement").attr("readOnly", false);
    //开启补录日报页面
    $('#daily-supplement').modal('show');
}

/**
 * 选中日期 判断日期是否已被录入过
 */
function ifSupplements(obj) {
    //获取日期
    var supplementDate = document.getElementById("ifSupplement").value;
    //为必填项
    if (supplementDate == null || supplementDate == "") {
        $MB.n_danger("日期为必填项");
        return false;
    }

    $.ajax({
        url: "dailyShow/ifSupplement",
        type: "post",
        data: {"supplementDate": supplementDate},
        dataType: "json",
        success: function (res) {
            if (res) {
                //数据的效验 false 为表示没有数据 true 表示今天添加了数据
                if (res.msg) {
                    $MB.n_danger("此时间段已经补录过日报");
                } else {
                    //禁止输入日期
                    $("#ifSupplement").attr("readOnly", true);
                    //添加日报
                    addIfSupplement(obj)
                }
            }

        },
        error: function (err) {
            $MB.n_danger("网络连接失败,稍后重试", err);
        }

    })
}

//补录日报的标记
var SupplementCoun = 0;

/**
 * 补录日报的inpu
 * @param obj
 */
function addIfSupplement(obj) {
    SupplementCoun++
    html =
        '<div class="row text-left"  id="add_supplementCoun' + SupplementCoun + '">' +

        '<div class="col-sm-11" >' +
        '<div class="input-group">' +
        '<span class="input-group-addon">项目代码：</span>' +
        '<div class="form-group">' +

        '<select multiple="multiple"  name="rolesSelect" id="rolesSelect' + SupplementCoun + '"></select>' +
        '<input  name="roles" hidden  id="projectNo_supplement' + SupplementCoun + '" ">' +
        '</div></div></div>' +

        '<div class="col-sm-11" >' +
        '<div class="input-group">' +
        '<span class="input-group-addon">测试类型：</span>' +
        '<div class="form-group">' +
        '<select class="form-control" id="articleType_supplement' + SupplementCoun + '">' +
        '<option value="" selected >请选择测试类型</option>' +
        '<option value="用例执行">用例执行</option>' +
        '<option value="专项执行">专项执行</option>' +
        '<option value="探索测试">探索测试</option>' +
        '<option value="缺陷/修改点验证、压测">缺陷/修改点验证、压测</option>' +
        '<option value="培训学习">培训学习</option>' +
        '<option value="组长事务">组长事务</option>' +
        '</select>' +
        '</div></div></div>' +

        '<div class="col-sm-11" >' +
        '<div class="input-group">' +
        '<span class="input-group-addon">用例条数：</span>' +
        '<div class="form-group">' +
        '<input type="text" onkeyup="value=value.replace(/[^\\d.]/g,\'\')"   class="form-control text-info" id="articleNumber_supplement' + SupplementCoun + '" placeholder="请输入项目测试用例条数">' +
        '</div></div></div>' +

        '<div class="col-sm-11" >' +
        '<div class="input-group">' +
        '<label  class="input-group-addon">计划投入工时：</label>' +
        '<div class="form-group">' +
        '<input type="text" onkeyup="value=value.replace(/[^\\d.]/g,\'\')" class="form-control text-info" id="plannedLaborHours_supplement' + SupplementCoun + '" placeholder="请输入计划投入工时">' +
        '</div></div></div>' +

        '<div class="col-sm-11" >' +
        '<div class="input-group">' +
        '<label class="input-group-addon ">实际投入工时：</label>' +
        '<div class="form-group">' +
        '<input type="text" onkeyup="value=value.replace(/[^\\d.]/g,\'\')" class="form-control text-info" id="actuaLinputHours_supplement' + SupplementCoun + '" placeholder="请输入实际投入工时">' +
        '</div></div></div>' +

        '<div class="col-sm-11" >' +
        '<div class="input-group">' +
        '<label class="input-group-addon ">投入内容：</label>' +
        '<div class="form-group">' +
        '<input type="text" class="form-control text-info " id="inputContent_supplement' + SupplementCoun + '" placeholder="请输入投入内容">' +
        '</div></div></div>' +


        '<span class="input-group-btn">' +
        '<button class="btn btn-save" type="button" onclick="deleteSupplement()"   id="delSupplement">删除</button>' +
        '</span>' +

        '<div class="row" >' +
        '<span>------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------' +
        '</span>' +
        '</div>' +
        '</div>'
    obj.insertAdjacentHTML('beforebegin', html);
    initDailyShow(SupplementCoun)
}


/**
 * 补录日报的删除
 */
function deleteSupplement() {
    for (let i = 0; i < 20; i++) {
        //关闭所有inpu的
        var el = document.getElementById("add_supplementCoun" + i + "");
        el == null ? "" : el.remove();
    }
    //开启校验时间input
    $("#ifSupplement").attr("readOnly", false);
    SupplementCoun = 0;
}


//效率数
var percent;
//补录日报数据
var supplementJsonData;
//效率数
var percent;

/**
 * 按钮监听
 */
$("#daily-supplement .btn-save").click(function () {
    var name = $(this).attr("name");
    //存数据的集合
    var rewardArray = new Array();

    //关闭页面
    if (name === "close_supplement") {
        //关闭页面
        $('#daily-supplement').modal('hide');
        //关闭以后删除所有日报input
        deleteSupplement()

        //下一步按钮
    } else if (name === "save_supplement") {
        //取到动态输入的值
        for (var i = 1; i <= SupplementCoun; i++) {
            //项目代码
            var projectNo = $('div .input-group #projectNo_supplement' + i).val();
            //计划投入工时
            var plannedLaborHours = $('div .input-group #plannedLaborHours_supplement' + i).val();
            //实际投入工时
            var actuaLinputHours = $('div .input-group #actuaLinputHours_supplement' + i).val();
            //投入内容
            var inputContent = $('div .input-group #inputContent_supplement' + i).val();
            //测试用例条数
            var articleNumber = $('div .input-group #articleNumber_supplement' + i).val();
            //测试类型
            var articleType = $('div .input-group #articleType_supplement' + i).val();
            //判断有没有填
            if (
                //项目代码
                (projectNo == "" || projectNo == undefined) ||
                //计划投入工时
                (plannedLaborHours == "" || undefined == plannedLaborHours) ||
                //实际投入工时
                (actuaLinputHours == "" || undefined == actuaLinputHours) ||
                //投入内容
                (inputContent == "" || undefined == inputContent) ||
                //测试用例条数
                (articleNumber == "" || undefined == articleNumber)||
                //测试类型
                (articleType == "" || undefined == articleType)) {
                $MB.n_danger("亲！六项都为必填哦");
                rewardArray = [];
                break
            } else {
                if (
                    //项目代码
                    (projectNo != "" && projectNo != undefined) &&
                    //计划投入工时
                    (plannedLaborHours != "" && undefined != plannedLaborHours) &&
                    //实际投入工时
                    (actuaLinputHours != "" && undefined != actuaLinputHours) &&
                    //投入内容
                    (inputContent != "" && undefined != inputContent) &&
                    //测试用例条数
                    (articleNumber != "" && undefined != articleNumber)&&
                    //测试类型
                    (articleType != "" &&  undefined != articleType)) {
                    var obj = new Object();
                    //项目代码
                    obj['projectNo'] = projectNo;
                    //计划投入工时
                    obj['plannedLaborHours'] = plannedLaborHours;
                    //实际投入工时
                    obj['actuaLinputHours'] = actuaLinputHours;
                    //投入内容
                    obj['inputContent'] = inputContent;
                    //测试条例
                    obj['articleNumber'] = articleNumber;
                    //测试类型
                    obj['articleType'] = articleType;
                    rewardArray.push(obj);
                }
            }

        }

        if (rewardArray.length > 0) {
            //计划
            var plannedLaborHoursNum = 0;
            //实际投入工时
            var actuaLinputHoursNum = 0;
            rewardArray.forEach(obj => {
                plannedLaborHoursNum += parseFloat(obj.plannedLaborHours);
                actuaLinputHoursNum += parseFloat(obj.actuaLinputHours);
            });
            //当日的总计划 /实际投入
            percent = (plannedLaborHoursNum / actuaLinputHoursNum) * 100;
            //效率
            var executionefFiciency = parseInt(percent).toString() + "%";
            //效率赋值
            $("#executioneFficiency_supplement").val(executionefFiciency);
            //打开模态框
            $('#daily-add-supplement').modal('show')
            //日报数据
            supplementJsonData = JSON.stringify(rewardArray);
            rewardArray = [];
        }
    }
});

//下一步的窗口 提交触发
//防止按钮重复提交 补录日报
var issubmit = false;
$("#daily-add-supplement .btn-save").click(function () {
    var name = $(this).attr("name");
    //提交
    if (name === "supplement_add") {
        //点击按钮屏蔽一次防止多次触发
        $("#supplement_add").attr("disabled", true);
        //执行效率
        var executioneFficiency = $("#executioneFficiency_supplement").val();
        //执行效率原因
        var reasonsforeFficiencyFailure = $("#reasonsforeFficiencyFailure_supplement").val();
        //获取补录日期
        var supplementDate = $("#ifSupplement").val();
        //执行效率低于百分之90
        if (percent < 90) {
            //不为空
            if (reasonsforeFficiencyFailure == null || reasonsforeFficiencyFailure == "") {
                $MB.n_danger("亲！ 效率不达标 原因为必填项哦");
                //点击按钮屏蔽一次防止多次触发
                $("#supplement_add").attr("disabled", false);
                return;
            }
        }

        //发送数据
        $.post(ctx + "dailyShow/supplementAdd", {
            "daily": supplementJsonData,
            "executioneFficiency": executioneFficiency,
            "reasonsforeFficiencyFailure": reasonsforeFficiencyFailure,
            "supplementDate": supplementDate
        }, function (r) {

            if (r.code === 0) {
                //关闭效率页面
                $('#daily-supplement').modal('hide');
                //关闭日报添加页面
                $('#daily-add-supplement').modal('hide');
                //关闭所有inpu的
                deleteSupplement();
                //点击按钮屏蔽一次防止多次触发
                $("#supplement_add").attr("disabled", false);
                //刷新
                $MB.refreshTable("dailyShowTable");
                $MB.n_success(r.msg);
            } else {
                //点击按钮屏蔽一次防止多次触发
                $("#supplement_add").attr("disabled", false);
                $MB.n_danger(r.msg);
            }
        });
    }

});

/**
 * 动态下拉款
 * @param obj
 */
function initDailyShow(obj) {
    $.post(ctx + "projectNum/list", {}, function (r) {
        var data = r.rows;
        var option = "";
        for (var i = 0; i < data.length; i++) {
            option += "<option value='" + data[i].projectNum + "'>" + data[i].projectNum + "</option>"
        }
        //动态拼接
        $('#rolesSelect' + obj).html("").append(option);
        var options = {
            placeholder: "请选择",
            //是否有全显
            selectAll: false,
            allSelected:'选择全部',
            single: false,
            width: '100%',
            onClose: function () {
                //回显
                $('#projectNo_supplement' + obj).val($('#rolesSelect' + obj).val());
            }
        };
        $('#rolesSelect' + obj).multipleSelect(options);
    });
}
